package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.pay.AlipayConfig;
import cn.wolfcode.shop.cloud.pay.AlipayProperties;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.netflix.client.IResponse;
import org.apache.tomcat.util.log.SystemLogHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import static java.lang.System.out;

@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private IOrderInfoService orderInfoService;
    @RequestMapping("/payOrder")
    public void payOrder(String orderNo, HttpServletResponse response) throws Exception {
        //获取订单信息
        OrderInfo orderInfo = orderInfoService.getOrderInfoByOderNo(orderNo);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置同步回调地址
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        //设置异步回调地址
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no=orderNo;
        //付款金额，必填
        String total_amount = orderInfo.getSeckillPrice() + "";
        //订单名称，必填
        String subject =orderInfo.getGoodName();
        //商品描述，可空
        String body =orderInfo.getGoodName();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //输出
        out.println(result);
    }
    /**
     * 异步请求处理逻辑业务，同步请求负责显示数据
     *
     * 异步请求比同步更快
     */
    @RequestMapping("/returnUrl")
    //获取反馈回来的参数
    public void returnUrl(@RequestParam Map params,HttpServletResponse response) throws Exception {
        System.out.println(new Date());

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //重定向到订单详情页面
            response.sendRedirect("http://localhost/order_detail.html?orderNo="+params.get("out_trade_no"));
            }else {
//跳转到错误页面
            response.sendRedirect("http://localhost/50.html");
        }
    }

    //异步回调
    @RequestMapping("/notifyUrl")
    public void notifyUrl(@RequestParam Map params,HttpServletResponse response) throws Exception {
        //页签
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSign_type()); //调用SDK验证签名
        PrintWriter out = response.getWriter();
        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if(signVerified) {//验证成功
            //商户订单号
            String orderNo = params.get("out_trade_no") + "";
            //修改订单状态
            orderInfoService.updateOrderStatus(orderNo,OrderInfo.STATUS_ACCOUNT_PAID);
            //支付宝交易号

            //交易状态
            out.println("success");

        }else {//验证失败
           out.println("fail");

        }
    }
}
